package com.bort.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bort.system.info.CostInfo;
import com.bort.system.info.OrderInfo;
import com.bort.system.mapper.CostMapper;
import com.bort.system.mapper.GoodsMapper;
import com.bort.system.mapper.OrderMapper;
import com.bort.system.model.Cost;
import com.bort.system.model.TOrder;
import com.bort.system.model.User;
import com.bort.system.service.TOrderService;
import com.bort.system.utils.DateUtils;
import com.bort.system.utils.Result;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
public class TOrderServiceImpl extends ServiceImpl<OrderMapper, TOrder> implements TOrderService {

    @Resource
    OrderMapper orderMapper;

    @Resource
    CostMapper costMapper;

    @Override
    public Result<Page<OrderInfo>> getOrderList(Page<OrderInfo> pager, Map<String, Object> map) {
        List<OrderInfo> list = orderMapper.getOrderList(pager,map);
        pager.setRecords(list);
        return Result.success(pager);
    }


    @Override
    public Result<Map<String, BigDecimal>> dataStatistic(Map<String, Object> map) {
        List<Map<Integer,Object>> business = orderMapper.businessStatus(map);
        Map<String,BigDecimal> data = new HashMap<>();
        for (Map<Integer, Object> buss : business) {
          if(buss.get("businessType") !=null) {
              BigDecimal payAmount = null != buss.get("payAmount")?new BigDecimal(buss.get("payAmount").toString()):BigDecimal.ZERO;
              int bType = Integer.parseInt(buss.get("businessType").toString());
              if(1==bType){
                  data.put("income",payAmount);
              } else if(2==bType){
                  data.put("outcome",payAmount);
              }
          }
        }
        if(data.get("income") == null){
            data.put("income",BigDecimal.ZERO);
        }
        if(data.get("outcome") == null){
            data.put("outcome",BigDecimal.ZERO);
        }

        BigDecimal earn = data.get("income").subtract(data.get("outcome"));
        data.put("earn",earn);

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,12);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        Date timeEnd = calendar.getTime();

        calendar.add(Calendar.DAY_OF_MONTH,-1);
        Date timeBegin = calendar.getTime();

        String begin = DateUtils.toStrTime(timeBegin);
        String end = DateUtils.toStrTime(timeEnd);

        Map<String,Object> yesterdayMap = new HashMap<>();
        yesterdayMap.put("businessType",1);
        yesterdayMap.put("timeBegin",begin);
        yesterdayMap.put("timeEnd",end);
        List<Map<Integer, Object>> yesterday = orderMapper.businessStatus(yesterdayMap);
        if(yesterday != null && yesterday.size() > 0){
            Map<Integer, Object> yesterdayIn = yesterday.get(0);
            BigDecimal payAmount = null != yesterdayIn.get("payAmount")?new BigDecimal(yesterdayIn.get("payAmount").toString()):BigDecimal.ZERO;
            data.put("yesterdayIn",payAmount);
        }else{
            data.put("yesterdayIn",BigDecimal.ZERO);
        }

        QueryWrapper<Cost> investWrapper = new QueryWrapper<>();
        investWrapper.eq("cost_type",10);
        investWrapper.eq("id",1);
        Cost invest = costMapper.selectOne(investWrapper);
        if(invest != null){
            data.put("invest",invest.getTotalAmount());
        }else{
            data.put("invest",BigDecimal.ZERO);
        }

        BigDecimal recovery = costMapper.getRecoverySum(map.get("timeBegin"),map.get("timeEnd"));
        if(recovery != null){
           data.put("recovery",recovery);
        }else{
            data.put("recovery",BigDecimal.ZERO);
        }

        return Result.success(data);
    }

    @Override
    public Result addCost(CostInfo costInfo) {
        if(costInfo != null){
            Date now = new Date();
            Subject subject = SecurityUtils.getSubject();
            User principal = (User) subject.getPrincipal();
            TOrder order = new TOrder();
            order.setBusinessType(2);
            order.setCreateUserId(principal.getId());
            order.setOrderStatus(1);
            order.setCreateTime(now);
            order.setTotal(costInfo.getRealPay());
            order.setRealPay(costInfo.getRealPay());
            String orderNo = "SN"+ RandomStringUtils.randomAlphanumeric(5)+System.currentTimeMillis();
            order.setOrderNo(orderNo);
            save(order);
            List<Cost> costList = costInfo.getCostList();
            if(costList != null && costList.size() > 0){
                for (Cost cost : costList) {
                    cost.setOrderId(order.getId());
                    cost.setCreateTime(now);
                    cost.setCreateUserId(principal.getId());
                    costMapper.insert(cost);
                    if(cost.getCostType() == 1){
                        updateGoodsStock(cost.getGoodsId(),cost.getStock());
                    }
                }
            }
            return Result.success();
        }else{
            return Result.error("数据有误,下单失败");
        }
    }

    private void updateGoodsStock(Integer goodsId, Integer stock) {
        costMapper.increaseGoodsStock(goodsId,stock);
    }

}
